package com.fc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fc.dto.TableDTO;
import com.fc.entity.SysPageSet;
import com.fc.entity.SysTable;
import com.fc.mapper.SysTableMapper;
import com.fc.service.SysPageSetService;
import com.fc.service.SysTableService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.query.QueryUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 代码生成表 服务实现类
 * </p>
 *
 * @author zffc
 * @since 2023-07-20
 */
@Service
public class SysTableServiceImpl extends ServiceImpl<SysTableMapper, SysTable> implements SysTableService {
    @Autowired
    private SysPageSetService sysPageSetService;

    @Override
    public String saveBatchTable(List<TableDTO> list) {
        List<SysTable> tableList = new ArrayList<SysTable>();
        StringBuffer message = new StringBuffer();
        for(TableDTO dto:list){
            if(!isExist(dto.getTableName())){
               SysTable table = new SysTable(dto.getTableName(),0,dto.getDescription());
               tableList.add(table);
            }else{
                message.append(dto.getTableName())
                        .append("在数据库中已存在/n");
            }
        }
        saveBatch(tableList);
        return message.toString();

    }

    @Override
    public void addOrModify(SysTable sysTable) {
        saveOrUpdate(sysTable);
        LambdaQueryWrapper<SysPageSet> queryWrapper = new LambdaQueryWrapper<SysPageSet>();
        queryWrapper.eq(SysPageSet::getTableId,sysTable.getId());
        sysPageSetService.remove(queryWrapper);
        List<SysPageSet> list = sysTable.getPageSets();
        list.forEach( e->e.setTableId(sysTable.getId()));
        sysPageSetService.saveBatch(list);
    }

    private Boolean isExist(String name){
        LambdaQueryWrapper<SysTable> queryWrapper = new LambdaQueryWrapper<SysTable>();
        queryWrapper.eq(SysTable::getTableName,name);
        return getOne(queryWrapper) != null ? true: false;
     }
}
